package com.wichell.framework.interceptor;

import org.aopalliance.intercept.MethodInvocation;

import com.wichell.framework.bean.MsgBean;
import com.wichell.framework.util.JacksonUtil;

public class LogAdvice extends AbstractAdvice {
	private SendAdvice sendAdvice;
	private LogRequest logRequest;

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {

		MsgBean msg = packageMsg(invocation);
		long dtDate = System.currentTimeMillis();
		try {
			Object obj = invocation.proceed();
			msg.put("result", JacksonUtil.obj2Json(obj));
			msg.put("level", "INFO");
			return obj;
		} catch (Exception e) {
			msg.put("result", e.toString());
			msg.put("level", "ERROR");
			throw e;
		} finally {
			msg.put("runTime", System.currentTimeMillis() - dtDate);
			sendAdvice.addMessage(msg);
		}
	}

	public SendAdvice getSendAdvice() {
		return sendAdvice;
	}

	public void setSendAdvice(SendAdvice sendAdvice) {
		this.sendAdvice = sendAdvice;
	}

	public LogRequest getLogRequest() {
		return logRequest;
	}

	public void setLogRequest(LogRequest logRequest) {
		this.logRequest = logRequest;
	}

	private MsgBean packageMsg(MethodInvocation invocation) {
		MsgBean msg = new MsgBean("log", "log");
		msg.put("className", invocation.getThis().getClass().getName());
		msg.put("methodName", invocation.getMethod().getName());
		msg.put("param", paramToString(invocation.getArguments()));
		msg.put("requestId", logRequest.getRequestId());
		return msg;
	}
}
